package top.dimples.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.dimples.common.interceptor.AdminInterceptor;
import top.dimples.common.interceptor.LoginInterceptor;
import top.dimples.common.interceptor.WebInterceptor;
import top.dimples.resovler.CustomArugsResovler;

import java.util.List;

@Configuration
public class MyWebConfiguration implements WebMvcConfigurer {

    @Autowired
    private CustomArugsResovler customArugsResovler;

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("admin/index");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(customArugsResovler);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] ignoreUrl = {
                "/api/user/login",
                "/api/user/checkFindPassword",
                "/api/user/changeFindPassword",
                "/api/user/forget",
                "/api/user/register",
                "/admin/user/login",
                "/api/lucky/info/{id}",
                "/**"
        };
        registry.addInterceptor(new LoginInterceptor()).order(0).addPathPatterns("/api/*/**", "/admin/*/**").excludePathPatterns(ignoreUrl);
        registry.addInterceptor(new WebInterceptor()).order(1).addPathPatterns("/api/*/**").excludePathPatterns(ignoreUrl);
        registry.addInterceptor(new AdminInterceptor()).order(1).addPathPatterns("/admin/*/**").excludePathPatterns(ignoreUrl);
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    private CorsConfiguration corsConfiguration() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration());
        return new CorsFilter(source);
    }
}
